{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="bi bi-send me-2"></i>已发送
        {% if emails.total > 0 %}
            <span class="badge bg-secondary">{{ emails.total }}</span>
        {% endif %}
    </h2>
    
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="refreshEmails()">
            <i class="bi bi-arrow-clockwise me-1"></i>刷新
        </button>
        <a href="{{ url_for('main.compose') }}" class="btn btn-primary">
            <i class="bi bi-pencil-square me-1"></i>写邮件
        </a>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-8">
                <div class="input-group">
                    <span class="input-group-text">
                        <i class="bi bi-search"></i>
                    </span>
                    <input type="text" class="form-control" name="search" 
                           value="{{ request.args.get('search', '') }}" 
                           placeholder="搜索邮件主题或内容...">
                </div>
            </div>
            <div class="col-md-4">
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                    {% if request.args.get('search') %}
                        <a href="{{ url_for('main.sent') }}" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle me-1"></i>清除
                        </a>
                    {% endif %}
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 邮件列表 -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span>
            {% if request.args.get('search') %}
                搜索结果 ({{ emails.total }} 封邮件)
            {% else %}
                已发送邮件
            {% endif %}
        </span>
        
        {% if emails.total > 0 %}
            <div class="btn-group btn-group-sm">
                <button class="btn btn-outline-danger" onclick="deleteSelected()" 
                        title="删除选中" id="deleteSelectedBtn" disabled>
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        {% endif %}
    </div>
    
    <div class="card-body p-0">
        {% if emails.items %}
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th width="40">
                                <input type="checkbox" id="selectAll" class="form-check-input">
                            </th>
                            <th width="60">状态</th>
                            <th>收件人</th>
                            <th>主题</th>
                            <th width="150">时间</th>
                            <th width="100">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for email in emails.items %}
                            <tr class="email-item" data-email-id="{{ email.id }}">
                                <td>
                                    <input type="checkbox" class="form-check-input email-checkbox" 
                                           value="{{ email.id }}">
                                </td>
                                <td>
                                    {% if email.is_read %}
                                        <i class="bi bi-envelope-open-fill text-success" title="已读"></i>
                                    {% else %}
                                        <i class="bi bi-envelope-fill text-muted" title="未读"></i>
                                    {% endif %}
                                </td>
                                <td>
                                    <strong>{{ email.recipient.username }}</strong>
                                    <br>
                                    <small class="text-muted">{{ email.recipient.email }}</small>
                                </td>
                                <td>
                                    <a href="{{ url_for('main.view_email', email_id=email.id) }}" 
                                       class="text-decoration-none text-dark">
                                        <strong>{{ email.subject }}</strong>
                                        <br>
                                        <small class="text-muted">
                                            {{ email.content[:100] }}{% if email.content|length > 100 %}...{% endif %}
                                        </small>
                                    </a>
                                </td>
                                <td>
                                    <small class="text-muted">
                                        {{ email.sent_at.strftime('%Y-%m-%d %H:%M') }}
                                    </small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="{{ url_for('main.view_email', email_id=email.id) }}" 
                                           class="btn btn-outline-primary btn-sm" title="查看">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <button class="btn btn-outline-danger btn-sm" 
                                                onclick="deleteEmail({{ email.id }})" 
                                                title="删除">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        {% else %}
            <div class="text-center py-5">
                <i class="bi bi-send display-1 text-muted"></i>
                <h4 class="text-muted mt-3">
                    {% if request.args.get('search') %}
                        没有找到匹配的邮件
                    {% else %}
                        还没有发送过邮件
                    {% endif %}
                </h4>
                <p class="text-muted">
                    {% if not request.args.get('search') %}
                        <a href="{{ url_for('main.compose') }}" class="text-decoration-none">
                            发送第一封邮件
                        </a>
                    {% endif %}
                </p>
            </div>
        {% endif %}
    </div>
    
    <!-- 分页 -->
    {% if emails.pages > 1 %}
        <div class="card-footer">
            <nav aria-label="邮件分页">
                <ul class="pagination justify-content-center mb-0">
                    {% if emails.has_prev %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('main.sent', page=emails.prev_num, search=request.args.get('search', '')) }}">
                                <i class="bi bi-chevron-left"></i>
                            </a>
                        </li>
                    {% endif %}
                    
                    {% for page_num in emails.iter_pages() %}
                        {% if page_num %}
                            {% if page_num != emails.page %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('main.sent', page=page_num, search=request.args.get('search', '')) }}">
                                        {{ page_num }}
                                    </a>
                                </li>
                            {% else %}
                                <li class="page-item active">
                                    <span class="page-link">{{ page_num }}</span>
                                </li>
                            {% endif %}
                        {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">…</span>
                            </li>
                        {% endif %}
                    {% endfor %}
                    
                    {% if emails.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('main.sent', page=emails.next_num, search=request.args.get('search', '')) }}">
                                <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const emailCheckboxes = document.querySelectorAll('.email-checkbox');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    
    // 全选/取消全选
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            emailCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateDeleteButtonState();
        });
    }
    
    // 单个复选框变化
    emailCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateSelectAllState();
            updateDeleteButtonState();
        });
    });
    
    // 更新全选状态
    function updateSelectAllState() {
        if (!selectAllCheckbox) return;
        
        const checkedCount = document.querySelectorAll('.email-checkbox:checked').length;
        const totalCount = emailCheckboxes.length;
        
        selectAllCheckbox.checked = checkedCount === totalCount && totalCount > 0;
        selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < totalCount;
    }
    
    // 更新删除按钮状态
    function updateDeleteButtonState() {
        if (!deleteSelectedBtn) return;
        
        const checkedCount = document.querySelectorAll('.email-checkbox:checked').length;
        deleteSelectedBtn.disabled = checkedCount === 0;
    }
    
    // 点击邮件行（除了复选框和按钮）跳转到详情
    document.querySelectorAll('.email-item').forEach(row => {
        row.addEventListener('click', function(e) {
            // 如果点击的是复选框、按钮或链接，不执行跳转
            if (e.target.type === 'checkbox' || 
                e.target.tagName === 'BUTTON' || 
                e.target.tagName === 'A' ||
                e.target.closest('button') ||
                e.target.closest('a')) {
                return;
            }
            
            const emailId = this.dataset.emailId;
            if (emailId) {
                window.location.href = `/email/${emailId}`;
            }
        });
    });
});

// 刷新邮件列表
async function refreshEmails() {
    window.location.reload();
}

// 删除单封邮件
async function deleteEmail(emailId) {
    if (!confirm('确定要删除这封邮件吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`/api/emails/${emailId}/delete`, {
            method: 'POST'
        });
        
        if (response.success) {
            // 移除行
            const row = document.querySelector(`[data-email-id="${emailId}"]`);
            if (row) {
                row.remove();
            }
            
            showAlert(response.message, 'success');
            
            // 如果页面没有邮件了，刷新页面
            const remainingEmails = document.querySelectorAll('.email-item');
            if (remainingEmails.length === 0) {
                setTimeout(() => window.location.reload(), 1000);
            }
        }
    } catch (error) {
        showAlert(error.message, 'danger');
    }
}

// 删除选中的邮件
async function deleteSelected() {
    const selectedCheckboxes = document.querySelectorAll('.email-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        showAlert('请选择要删除的邮件', 'warning');
        return;
    }
    
    if (!confirm(`确定要删除选中的 ${selectedCheckboxes.length} 封邮件吗？`)) {
        return;
    }
    
    const promises = [];
    selectedCheckboxes.forEach(checkbox => {
        const emailId = checkbox.value;
        promises.push(
            apiRequest(`/api/emails/${emailId}/delete`, { method: 'POST' })
                .catch(error => ({ error: error.message, emailId }))
        );
    });
    
    try {
        const results = await Promise.all(promises);
        const errors = results.filter(r => r.error);
        
        if (errors.length === 0) {
            showAlert('选中的邮件已删除', 'success');
        } else {
            showAlert(`${promises.length - errors.length} 封邮件已删除，${errors.length} 封失败`, 'warning');
        }
        
        // 刷新页面
        setTimeout(() => window.location.reload(), 1000);
    } catch (error) {
        showAlert('批量删除失败', 'danger');
    }
}
</script>
{% endblock %}